import React = require("react");
import { PageProps } from "maishu-chitu-react";
import { DesignView } from "controls/design-view";
import { pageDatas, findChildComponentData } from "services/page-datas";
import { LocalService } from "services/local-service";
import { Menu, Props as MenuProps, State as MenuState, MenuNode, MenuStorageName, defaultShowIcon } from "components/menu/component";
import { ValueStore } from "maishu-chitu";
import * as ui from "maishu-ui-toolkit";
import { ItemDialog } from "controls/item-dialog";
import { asyncComponentState } from "common";
import { PageDataRecord } from "entities";

interface State {
    // menu?: Menu;
    showIcon: boolean
    pageDataRecord?: PageDataRecord
}
export default class StoreMenuPage extends React.Component<PageProps, State> {
    localService: LocalService;
    designPage: DesignView;
    menuState = new ValueStore<MenuState>()
    menu: Menu;
    menuNodeList: MenuNodeList;
    // isAsyncMenuAndMenuNodeList: boolean = false;

    constructor(props) {
        super(props);

        this.state = { showIcon: false };
        this.localService = this.props.createService(LocalService);
    }

    async loadData() {
        let pageDataRecord = await pageDatas.menu();
        console.assert(pageDataRecord != null);

        let menuComponentData = findChildComponentData(pageDataRecord.pageData, Menu.name);
        console.assert(menuComponentData != null);
        let menuProps = (menuComponentData.props as MenuProps);

        let menuRef = menuProps.ref;
        menuProps.ref = (menu) => {
            if (!menu || this.menu) return;

            if (typeof menuRef == "function")
                menuRef(menu);

            this.menu = menu;
            this.asyncMenuAndMenuNodeList();
        }

        return { pageData: pageDataRecord };
    }

    asyncMenuAndMenuNodeList() {
        // if (this.isAsyncMenuAndMenuNodeList)
        //     return;

        if (this.menu == null || this.menuNodeList == null)
            return;

        // this.isAsyncMenuAndMenuNodeList = true;
        asyncComponentState(this.menu, this.menuNodeList, "menuNodes");
        asyncComponentState(this.menu, this, "showIcon");
    }

    async componentDidMount() {
        let { pageData: pageDataRecord } = await this.loadData();
        this.setState({ pageDataRecord });
    }

    render() {

        let { pageDataRecord, showIcon } = this.state;
        showIcon = showIcon == null ? defaultShowIcon : showIcon;
        if (pageDataRecord == null) {
            return <div className="empty">数据正在加载中...</div>
        }

        return <DesignView ref={e => this.designPage = e || this.designPage}
            {...this.props} pageDataRecord={pageDataRecord}
            hideEditorPanel={true} hideToolbar={true} hidePageSettingPanel={true}>
            <div className="menuEditor">
                <div className="menu-apply">
                    <div className="pull-left">
                        <label className="pull-right">
                            <input type="checkbox" className="ace ace-switch ace-switch-5"
                                checked={showIcon}
                                onChange={(e) => {
                                    this.setState({ showIcon: e.target.checked });
                                }}
                            />
                            <span className="lbl middle"></span>
                        </label>
                        <div className="pull-right" style={{ padding: '4px 10px 0 0' }}>
                            菜单项显示图标
                        </div>
                    </div>
                    <div className="clear-fix" />
                </div>
                <MenuNodeList ref={e => {
                    if (!e) return;
                    this.menuNodeList = e;
                    this.asyncMenuAndMenuNodeList()

                }} {...{ showIcon }} />
            </div>
        </DesignView>
    }
}


type Link = {
    text: string,
    url: string
}

let links: Link[] = [
    { text: '请选择链接', url: '' },
    { text: '店铺主页', url: '#home_index' },
    { text: '购物车', url: '#shopping_shoppingCart' },
    { text: '会员主页', url: '#user_index' },
    { text: '商品类别', url: '#home_class' }
]

let icons = [
    "icon-home", "icon-shopping-cart", "icon-user", "icon-comment",
    "icon-rss", "icon-truck", "icon-reorder", "icon-calendar",
    "icon-th-large"
]

class MenuNodeList extends React.Component<
    { showIcon: boolean },
    { menuNodes: MenuNode[] }> {
    menuNodeDialog: MenuNodeDialog;

    constructor(props) {
        super(props);
        this.state = { menuNodes: [] };
    }
    newItem() {
        this.menuNodeDialog.show({} as MenuNode, "添加菜单项", (item) => {
            let { menuNodes } = this.state;
            menuNodes.push(item);
            this.setState({ menuNodes });
        });
    }
    editItem(item: MenuNode) {
        this.menuNodeDialog.show(item, "编辑菜单项", () => {
            let { menuNodes } = this.state;
            this.setState({ menuNodes });
        })
    }
    async deleteItem(menuItem: MenuNode) {
        let menuNodes = this.state.menuNodes.filter(o => o != menuItem);
        this.setState({ menuNodes });
    }
    linkName(url: string) {
        let link = links.filter(o => o.url == url)[0];
        return link ? link.text : '';
    }
    render() {
        let { menuNodes } = this.state;
        menuNodes = menuNodes || [];
        menuNodes.sort((a, b) => {
            return (a.sortNumber || 0) - (b.sortNumber || 0);
        });
        return <>
            <ul className="menu">
                {menuNodes.map((o, i) =>
                    <li key={i} style={{ display: "flow-root" }}>
                        <div className="pull-left" style={{ width: 60 }}>
                            {o.sortNumber}
                        </div>
                        <div className="pull-left" style={{ width: 100 }}>
                            {o.name}
                        </div>
                        <div className="pull-left">
                            {o.url} {this.linkName(o.url) ? `(${this.linkName(o.url)})` : ''}
                        </div>
                        <div className="pull-right">
                            <button className="btn btn-danger btn-sm pull-right" style={{ marginLeft: 4 }}
                                ref={(e: HTMLButtonElement) => {
                                    if (!e) return;
                                    e.onclick = ui.buttonOnClick(() => this.deleteItem(o), { confirm: `确定要删除菜单项 "${o.name}" 吗?` });
                                }}>
                                <i className="icon-remove" />
                                <span style={{ paddingLeft: 4 }}>删除</span>
                            </button>
                            <button className="btn btn-info btn-sm pull-right"
                                ref={(e: HTMLButtonElement) => {
                                    if (!e) return;
                                    e.onclick = () => this.editItem(o);
                                }}>
                                <i className="icon-pencil" />
                                <span style={{ paddingLeft: 4 }}>修改</span>
                            </button>
                        </div>
                    </li>
                )}
                <li>
                    <button className="btn btn-primary"
                        onClick={() => {
                            this.newItem();
                        }}>
                        <i className="icon-plus" />
                        <span>点击添加菜单项</span>
                    </button>
                </li>
            </ul>
            <MenuNodeDialog {...{ showIcon: this.props.showIcon, ref: (e) => this.menuNodeDialog = e || this.menuNodeDialog }} />
        </>
    }
}

class MenuNodeDialog extends ItemDialog<{ showIcon: boolean }, MenuNode> {
    private iconsElement: HTMLElement;

    private isCustomUrl() {
        if (this.state.item == null)
            return false;

        let currentUrl = this.state.item.url || "";
        let containsUrl = links.map(o => o.url).indexOf(currentUrl) >= 0;
        return !(containsUrl);
    }

    private toggleIconsPanel() {
        this.iconsElement.style.display ?
            this.iconsElement.style.removeProperty('display') :
            this.iconsElement.style.display = 'none';
    }

    render() {
        let { showIcon } = this.props;
        let { item: currentItem } = this.state || {} as this["state"];
        return <>
            <div className="form-horizontal">
                <div className="form-group">
                    <label className="col-sm-2 control-label">名称*</label>
                    <div className="col-sm-10">
                        <input name="name" type="text" className="form-control" placeholder="请输入菜单项名称"
                            value={currentItem.name || ""}
                            onChange={e => {
                                currentItem.name = e.target.value;
                                this.setState({ item: currentItem })
                            }} />
                    </div>
                </div>
                <div className="form-group">
                    <label className="col-sm-2 control-label">序号</label>
                    <div className="col-sm-10">
                        <input name="sortNumber" type="text" className="form-control" placeholder="请输入菜单项序号"
                            value={currentItem.sortNumber || ""}
                            onChange={e => {
                                currentItem.sortNumber = Number.parseInt(e.target.value);
                                this.setState({ item: currentItem })
                            }} />
                    </div>
                </div>
                {showIcon ?
                    <div className="form-group">
                        <label className="col-sm-2 control-label">图标</label>
                        <div className="col-sm-10">
                            <div className="input-group">
                                <input name="icon" type="text" className="form-control" placeholder="请输入菜单项图标"
                                    value={currentItem.icon || ""}
                                    onChange={e => {
                                        currentItem.icon = e.target.value;
                                        this.setState({ item: currentItem });
                                    }} />
                                <div className="input-group-addon"
                                    onClick={() => this.toggleIconsPanel()}>
                                    <i className="icon-cog" style={{ cursor: 'pointer' }} />
                                </div>
                                <div ref={(e: HTMLElement) => this.iconsElement = e || this.iconsElement} style={{
                                    position: 'absolute', height: 100, width: '100%', background: 'white',
                                    zIndex: 10, left: 0, top: 35, border: 'solid 1px #ccc', overflowY: 'auto',
                                    display: 'none'
                                }}>
                                    <div style={{ position: 'absolute', width: '100%', borderBottom: 'solid 1px #ccc', padding: '4px 6px', background: 'white' }}>
                                        <span>请选择图标</span>
                                        <i className="icon-remove" style={{ position: 'absolute', right: 6, top: 6 }}
                                            onClick={() => this.toggleIconsPanel()} />
                                    </div>
                                    <div style={{ padding: '30px 6px 6px 6px' }}>
                                        {icons.map(o =>
                                            <i key={o} className={o} style={{ display: 'table-cell', padding: 10, fontSize: 20 }}
                                                onClick={() => {
                                                    currentItem.icon = o;
                                                    this.toggleIconsPanel();
                                                    this.setState({ item: currentItem });
                                                }} />
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div> : null
                }
                <div className="form-group">
                    <label className="col-sm-2 control-label">链接*</label>
                    <div className="col-sm-10">
                        <input name="url" className="form-control"
                            style={{ display: this.isCustomUrl() ? null : 'none' }}
                            ref={(e: HTMLInputElement) => {
                                if (!e) return;
                                e.value = currentItem.url || '';
                                e.onchange = () => {
                                    currentItem.url = e.value;
                                }
                            }} />
                        <select className="form-control"
                            style={{ display: this.isCustomUrl() ? 'none' : null }}
                            ref={(e: HTMLSelectElement) => {
                                if (!e) return;
                                e.value = currentItem.url;
                                e.onchange = () => {
                                    let option = e.options[e.selectedIndex] as HTMLOptionElement;
                                    currentItem.url = option.value;
                                }
                            }}>
                            {links.map((o, i) =>
                                <option key={i} value={o.url}>
                                    {o.text}
                                </option>
                            )}

                        </select>
                    </div>
                </div>
                <div className="form-group">
                    <div className="col-sm-offset-2 col-sm-10">
                        <input type="checkbox"
                            ref={(e: HTMLInputElement) => {
                                if (!e) return;
                                e.value = currentItem.url || '';
                                e.checked = this.isCustomUrl();
                                e.onchange = () => {
                                    if (e.checked) {
                                        this.state.item.url = null;
                                        this.setState(this.state);
                                    }
                                    else {
                                        this.state.item.url = '';
                                        this.setState(this.state);
                                    }
                                }

                            }} /> 自定义链接
                            </div>
                </div>
            </div>


        </>
    }
}